package yijy.threadExample;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by yijy on 2017/7/26.
 * 给定时器启动的线程设置后台线程，主线程结束，后台线程跟着结束，负责一直不能结束
 */
public class TimerTest extends Thread{
    private int a;
    private static int count;

    public void start(){
        super.start();
        Timer timer = new Timer(true);//将与其相关的线程变为后台线程
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                while (true){
                    reset();
                    try {
                        sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        timer.schedule(task,10,500);//设置定时任务
    }

    public void reset(){
        a=0;
    }

    @Override
    public void run() {
        super.run();
        while (true){
            System.out.println(getName()+":"+a++);
            if(count++==1000)
                break;
            yield();
        }
    }

    public static void main(String[] args) {
        TimerTest timerTest = new TimerTest();
        timerTest.start();
    }
}
